#include "userdef.h"

#define ENCODER_PHASE_0 0
#define ENCODER_PHASE_1 2
#define ENCODER_PHASE_2 3
#define ENCODER_PHASE_3 1

#define B01 1
#define B10 2

#define ENCODER_DIRECTON 1

#define ENCODER_SPIN(_E1, _E2) switch (last_enc) { case _E1: encoder_diff += ENCODER_DIRECTON; break; case _E2: encoder_diff -= ENCODER_DIRECTON; }

#define ENCODER_PULSES_PER_STEP 5
#define EPPS ENCODER_PULSES_PER_STEP

void encoder_init(void)
{
	ENCODER_A_INIT();
	ENCODER_B_INIT();
	ENCODER_EN_INIT();		
}

void encoder_ec11_scan(void)
{
	uint8_t enc = 0;
	static uint8_t last_enc =0;

	if (!ENCODER_A) enc |= B01;
	if (!ENCODER_B) enc |= B10;
	
	if(enc!=last_enc)
	{
		switch(enc)
		{
			case ENCODER_PHASE_0: ENCODER_SPIN(ENCODER_PHASE_3, ENCODER_PHASE_1); break;
			case ENCODER_PHASE_1: ENCODER_SPIN(ENCODER_PHASE_0, ENCODER_PHASE_2); break;
			case ENCODER_PHASE_2: ENCODER_SPIN(ENCODER_PHASE_1, ENCODER_PHASE_3); break;
			case ENCODER_PHASE_3: ENCODER_SPIN(ENCODER_PHASE_2, ENCODER_PHASE_0); break;			
		}
		last_enc =enc;
	}
}









